import win32wnet
import win32security
import ntsecuritycon as con
import os
import win32wnet
import win32api  # 尝试通过 win32api 导入 pywintypes
from win32com.client import Dispatch
import ctypes
import os

class NETRESOURCE(ctypes.Structure):
    _fields_ = [
        ("dwScope", ctypes.c_ulong),
        ("dwType", ctypes.c_ulong),
        ("dwDisplayType", ctypes.c_ulong),
        ("dwUsage", ctypes.c_ulong),
        ("lpLocalName", ctypes.c_wchar_p),
        ("lpRemoteName", ctypes.c_wchar_p),
        ("lpComment", ctypes.c_wchar_p),
        ("lpProvider", ctypes.c_wchar_p),
    ]

def connect_to_share(share_root, username, password):
    net_resource = NETRESOURCE()
    net_resource.dwType = 0x00000001  # RESOURCETYPE_DISK
    net_resource.lpRemoteName = share_root

    result = ctypes.windll.mpr.WNetAddConnection2W(
        ctypes.byref(net_resource),
        password,
        username,
        0
    )

    if result != 0:
        print(f"Failed to connect to share: Error code {result}")
        return False
    return True

def disconnect_from_share(share_root):
    try:
        win32wnet.WNetCancelConnection2(share_root, 0, True)
    except Exception as e:
        print(f"Failed to disconnect from share: {e}")

def get_file_security(file_path):
    try:
        # 获取文件的安全对象
        sd = win32security.GetFileSecurity(file_path, win32security.DACL_SECURITY_INFORMATION)
        
        # 获取DACL（自由访问控制列表）
        dacl = sd.GetSecurityDescriptorDacl()
        
        print(f"Permissions for file: {file_path}")
        
        for i in range(0, dacl.GetAceCount()):
            ace = dacl.GetAce(i)
            sid = ace[2]
            
            try:
                user, domain, type = win32security.LookupAccountSid(None, sid)
                user_info = f"{domain}\\{user}"
            except pywintypes.error as e:
                user_info = f"SID: {sid}"
            
            access_mask = ace[1]
            
            # 解析权限
            permissions = []
            if access_mask & con.FILE_READ_DATA:
                permissions.append("READ")
            if access_mask & con.FILE_WRITE_DATA:
                permissions.append("WRITE")
            if access_mask & con.FILE_EXECUTE:
                permissions.append("EXECUTE")
            if access_mask & con.DELETE:
                permissions.append("DELETE")
            if access_mask & con.READ_CONTROL:
                permissions.append("READ_CONTROL")
            if not permissions:
                permissions.append("NO_PERMISSIONS_DETECTED")

            print(f"User/Group: {user_info}, Permissions: {', '.join(permissions)}")
    
    except Exception as e:
        print(f"Error occurred: {e}")

def main():
    import sys
    sys.path.append('path_to_pywin32')
    if len(sys.argv) < 2:
        print("Usage: python script.py <file_path>")
        sys.exit(1)

    file_path = sys.argv[1]
    # share_root = '\\\\10.70.222.232\\Public\\华星大数据分析\\大模型攻关会\\日会\\20250411\\AI大模型周会进展_20250411.pptx'
    # username = input("请输入NAS用户名: ")
    # password = input("请输入NAS密码: ")

    share_root = '\\\\10.70.222.232\\Public\\华星大数据分析\\大模型攻关会\\日会\\20250411\\AI大模型周会进展_20250411.pptx'
    username = "public"
    password = "tclpublic1"
    
    connect_to_share(share_root, username, password)

    if not connect_to_share(share_root, username, password):
        print("无法连接到NAS共享盘，请检查网络和凭据。")
        sys.exit(1)

    try:
        get_file_security(file_path)
    finally:
        disconnect_from_share(share_root)

if __name__ == "__main__":
    main()